#include "ifile_c.h"

dword	ifile_c::release()
{
	delete this;
	return 0;
}

bool	ifile_c::open(kcstr _filename)
{
	m_file_impl.open(_filename, "rb");
	if(is_open())
	{
		m_length_readed = m_file_impl.length();
		return true;
	}
	return false;
}

bool ifile_c::open(kcwstr _file_name)
{
	m_file_impl.open(_file_name, L"rb");
	if (is_open())
	{
		m_length_readed = m_file_impl.length();
		return true;
	}
	return false;
}


void	ifile_c::close()
{
	m_file_impl.close();
	m_length_readed = 0;
}

bool	ifile_c::is_open() const
{
	return m_file_impl.is_open();
}

bool	ifile_c::seek(dword _offset, file::seek_dir _dir)
{
	return m_file_impl.seek(_offset, _dir);
}

dword	ifile_c::tell() const
{
	return m_file_impl.tell();
}

dword	ifile_c::length() const
{
	return m_file_impl.length();
}

dword	ifile_c::length_readed() const
{
	return m_length_readed;
}

dword	ifile_c::read(void* _mem, dword _size)
{
	dword readed_len = m_file_impl.read(_mem, _size);
	if(readed_len)
	{
		m_length_readed = (m_length_readed >= readed_len) ?
			(m_length_readed - readed_len) : 0;
	}
	return readed_len;
}

kcstr	ifile_c::name() const
{
	return m_file_impl.name();
}

ifile*	io::create_ifile()
{
	return new ifile_c();
}

ifile*	io::read_file(kcstr _filename)
{
	ifile* f = create_ifile();
	if(f->open(_filename))
	{
		return f;
	}
	else
	{
		cmn::safe_release(f);
		return nullptr;
	}
}

ifile*	io::read_file(kcwstr _filename)
{
	ifile* f = create_ifile();
	if (f->open(_filename))
	{
		return f;
	}
	else
	{
		cmn::safe_release(f);
		return nullptr;
	}
}
